import React from 'react';
import { WeaSearchGroup, WeaFormItem, WeaLocaleProvider, WeaTools, WeaProgress, WeaUpload, WeaInput } from 'ecCom';
import { Button, Form } from 'antd';
import { toJS } from 'mobx';
import { WeaSwitch } from 'comsMobx';
import { inject, observer } from 'mobx-react';
import GovernTag from '../governPoint/tag';
import _ from 'lodash';
import ProMain from "../pro/proMain";

const getLabel = WeaLocaleProvider.getLabel;
let Base64 = ecCom.WeaTools.Base64;

@inject('proinfoStore', 'taskStore', 'proStore')
@observer
class Condition extends React.Component {
  componentDidUpdate() {
    const { listStore2 } = this.props;
    if (listStore2) {
      listStore2.getuploadProjectRef(this.refs);
    }
  }

  render() {
    const { condition } = this.props.listStore;
    const { form, col, handleChange } = this.props;
    const { isFormInit } = form;
    let group = [];
    let condition_time = {
      width: '300px'
    };
    let onlyreadLine = {
      borderBottom: '1px solid #faf4f4',
      lineHeight: '26px',
    };
    const formParams = form.getFormParams();
    isFormInit && toJS(condition).map((c, index) => {
      let items = [];
      c.items = c.items || [];
      c.items.map((field, index) => {
        items.push({
          com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@pobz8g@${field.domkey[0]}`}
            label={`${field.label}`}
            labelCol={{ span: `${field.labelcol}` }}
            error={(field.viewAttr == 3 && form.getError(field))}// 必填提示
            tipPosition="bottom"
            wrapperCol={{ span: `${field.fieldcol}` }}
            style={field.viewAttr == 1 ? onlyreadLine : null}
          >
            {
              <div className='governProMain' style={field.formItemType == 'TIMERANGEPICKER' ? condition_time : null}>
                {
                  this.getFormItem(field, form, formParams, handleChange)
                }
              </div>
            }
          </WeaFormItem>),
          col: col || field.colSpan,
        });
      });

      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@d2mcw3@${index}`}  title={c.title} needTigger={true} showGroup={c.defaultshow} items={items} col={col} />);
    });

    return group;
  }





  // 获取表单渲染出的dom
  getFormItem(field, form, formParams, handleChange) {
    let dom;
    if (field.formItemType == 'RICHTEXT' && field.viewAttr == 1) { dom = this.richTextItem(field); } else if (field.domkey[0] == 'status') { dom = this.statusItem(field); } else if (field.domkey[0] == 'progress') { dom = this.progressItem(field); } else if (field.conditionType == 'UPLOAD') { dom = this.getUploadItem(field, form); } else if (field.conditionType == 'INPUT') {
      const { type } = this.props;
      if (type == 'project' || type == 'task') {
        dom = this.getInputEnter(field, form);
      } else if (typeof handleChange === 'function') {
          dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@e8nht9`} fieldConfig={field} form={form} formParams={formParams} onChange={handleChange} />;
        } else {
          dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@10nddh`} fieldConfig={field} form={form} formParams={formParams} onChange={this.onEditChange.bind(this, field, form)} />;
        }
    } else if (typeof handleChange === 'function') {
        dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@fexlmk`} fieldConfig={field} form={form} formParams={formParams} onChange={handleChange} />;
    } else {
        dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@qr8svs`} fieldConfig={field} form={form} formParams={formParams} onChange={this.onEditChange.bind(this, field, form)} />;
      }
    return dom;
  }

  getInputEnter(field, formB) {
    const domkey = WeaTools.getKey(field);
    const keyObj = formB.$(domkey);
    return (
      <div className="govern-wea-form-item">
          <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@14r9xi`} onPressEnter={() => { this.doSearch(); }} {...keyObj.bind()} />
      </div>
    );
  }

  doSearch() {
    const { type, proStore, taskStore } = this.props;
    if (type == 'project') {
      const { dataType, selectedTreeKey } = proStore;
      proStore.setDataType(dataType);
      const params = { dataType, fromSuperPage: false, isSuperSearch: false, categoryid: selectedTreeKey };
      proStore.doSearch(params);
    } else if (type == 'task') {
      const { dataType, selectedTreeKey } = taskStore;
      taskStore.setDataType(dataType);
      const params = { dataType, fromSuperPage: false, isSuperSearch: false, categoryid: selectedTreeKey };
      taskStore.doSearch(params);
    }
  }

  onEditChange(field, form, res, obj) { // #806151 概述：解决督办变更，数值类型字段将值清空保存后值仍存在的问题
    let str = obj.value;
    if (field.conditionType == 'INPUTNUMBER' && (typeof str == null || str == '' || str == 'undefined')) {
      let numberfield = {};
      numberfield[field.domkey] = '';
      form.updateFields(numberfield);// 数值类型的清空时 formParams里面会没有
    }
  }
  // 重定义富文本dom
  richTextItem(field) {
    if (_.has(field, 'value') && field.value != '' && field.viewAttr == 1) {
      return <div dangerouslySetInnerHTML={{ __html: Base64.decode(field.value) }} className="g-richText g-richText-font" />;
    }
  }
  // 重定义状态dom
  statusItem(field) {
    const { proinfoStore } = this.props;
    let isFinishTask = false;
    let isDiscard = false;
    if (proinfoStore.modelStore.isFinishTask || proinfoStore.modelStore.isDiscard) {
      isFinishTask = proinfoStore.modelStore.isFinishTask;
      isDiscard = proinfoStore.modelStore.isDiscard;
    }
    return <div><GovernTag ecId={`${this && this.props && this.props.ecId || ''}_GovernTag@uaz0ma`} record={field} isFinishTask={isFinishTask} isDiscard={isDiscard} /></div>;
  }
  // 重定义进度dom
  progressItem(field) {
    const { proinfoStore } = this.props;
    let percent = 0;
    let isFinishTask = false;
    if (proinfoStore.modelStore.isFinishTask) {
      isFinishTask = proinfoStore.modelStore.isFinishTask;
    }
    if (field.value != '' && field.value.indexOf('%') > 0) {
      percent = field.value.replace('%', '');
      if (proinfoStore.modelStore.percent == 0) {
        percent = percent;
      } else {
        percent = proinfoStore.modelStore.percent;
      }
    } else if (isFinishTask == true) {
      percent = 100;
    } else {
      percent = 0;
    }
    return <div><WeaProgress ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@83ymoe`} percent={percent} strokeColor="#28ce87" /></div>;
  }
  // 获取上传组件
  getUploadItem(field, form) {
    const { listStore2 } = this.props;
    let { uploadSize, updateForm, submitFlag } = listStore2;
    let upload = {};
    return (<WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@jn7esw`}
      ref={field.domkey[0]}
      viewAttr={field.viewAttr}
      uploadUrl={field.uploadUrl}
      category={field.category}
      autoUpload={field.otherParams.autoUpload}
      datas={field.datas}
      multiSelection={field.multiSelection}
      maxUploadSize={field.otherParams.maxUploadSize}
      getShowListDatas={(listT, listB) => {
        if (listB.length > 0 && listT == 0 && !submitFlag) {
          upload[field.domkey] = 'xk';
          form.updateFields(upload);// 赋值绕过检验规则
        }
        updateForm(listT, listB, upload, form, field, uploadSize);
      }}
    />);
  }
}
@inject('taskStore', 'topStore', 'proStore')
@observer
class ConditionNum extends React.Component {
  componentDidUpdate() {
    const { listStore2 } = this.props;
    if (listStore2) {
      listStore2.getuploadProjectRef(this.refs);
    }
  }
  render() {
    const { conditionNum } = this.props.listStore;
    const { formB, col, forceRefresh } = this.props;
    const { isFormInit } = formB;
    let flag = false;
    let group = [];
    let onlyreadLine = {
      borderBottom: '1px solid #faf4f4',
      lineHeight: '26px',
    };
    let isonlyRead = false;
    const formParams = formB.getFormParams();
    isFormInit && toJS(conditionNum).map((c, index) => {
      let items = [];
      c.items = c.items || [];
      c.items.map((field, index) => {
       if (_.has(formB.fieldMap, WeaTools.getKey(field))) {
        (field.viewAttr == 1) ? (isonlyRead = true) : (isonlyRead = false);
        items.push({
          com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@3dta49@${field.domkey[0]}`}
            label={`${field.label}`}
            labelCol={{ span: `${field.labelcol}` }}
            wrapperCol={{ span: `${field.fieldcol}` }}
          >
            {
              <div>
                {
                  this.getFormItem(field, formB, formParams)
                }
              </div>
            }
          </WeaFormItem>),
          col: col || field.colSpan,
        });
      } else { // #815725 概述：解决督办列表开启建模扩展，前端，来回切换左侧菜单，页面就空白的问题
        // xk:该问题是快速切换菜单导致form和field不符合即菜单A先请求切换菜单B时B先完成，然后再A完成导致错误 技术时间有限先暂时这样处理。应该是要引起父组件重新渲染即可。
        // console.log('error',toJS(field),toJS(formB.fieldMap),formB)
        flag = true;
      }
      });
      if (flag) {
        if (typeof forceRefresh === 'function') {
          forceRefresh(true);
        }
      }
      group.push(<div style={isonlyRead ? onlyreadLine : null}><WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@egrrw8@${index}`} title={c.title} needTigger={true} showGroup={c.defaultshow} items={items} col={col} /></div>);
    });
    return group;
  }
  // 获取表单渲染出的dom
  getFormItem(field, formB, formParams) {
    let dom;
    if (field.formItemType == 'RICHTEXT' && field.viewAttr == 1) { dom = this.richTextItem(field); } else if (field.domkey[0] == 'status') { dom = this.statusItem(field); } else if (field.domkey[0] == 'progress') { dom = this.progressItem(field); } else if (field.conditionType == 'UPLOAD') { dom = this.getUploadItem(field, formB); } else if (field.conditionType == 'INPUT') {
      const { type } = this.props;
      if (type == 'project' || type == 'task' || type == 'search' || type == 'taskAccount') {
        dom = this.getInputEnter(field, formB);
      } else {
        dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@8gj74g`} fieldConfig={field} form={formB} formParams={formParams} />;
      }
    } else { dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@rvut9w`} fieldConfig={field} form={formB} formParams={formParams} />; }
    return dom;
  }
  // 重定义富文本dom
  richTextItem(field) {
    if (_.has(field, 'value') && field.value != '' && field.viewAttr == 1) {
      return <div dangerouslySetInnerHTML={{ __html: Base64.decode(field.value) }} />;
    }
  }

  getInputEnter(field, formB) {
    const domkey = WeaTools.getKey(field);
    const keyObj = formB.$(domkey);
    return (
      <div className="govern-wea-form-item">
          <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@s8hcvc`} onPressEnter={() => { this.doSearch(); }} {...keyObj.bind()} />
      </div>
    );
  }

  doSearch() {
    const { type, proStore, taskStore, onEnterSearch } = this.props;
    if (type == 'project') {
      const { dataType, selectedTreeKey } = proStore;
      proStore.setDataType(dataType);
      const params = { dataType, fromSuperPage: true, isSuperSearch: true, categoryid: selectedTreeKey };
      proStore.doSearch(params);
    } else if (type == 'task') {
      const { dataType, selectedTreeKey } = taskStore;
      taskStore.setDataType(dataType);
      const params = { dataType, fromSuperPage: true, isSuperSearch: true, categoryid: selectedTreeKey };
      taskStore.doSearch(params);
    } else if (type == 'taskAccount') {
      const { taskAccountStore } = this.props;
      const { dataType } = taskStore;
      let { currentData } = taskAccountStore;
      const params = { dataType,
fromSuperPage: true,
isSuperSearch: true,
selectedTreeKey: taskAccountStore.selectedTreeKey,
      projid: currentData.projid,
prjCategory: currentData.prjCategory,
prjid: currentData.prjid };
      taskStore.doSearch(params);
    } else if (type == 'search') {

    }
    onEnterSearch(false);
  }

  // 重定义状态dom
  statusItem(field) {
    const { taskStore } = this.props;
    let isFinishTask = false;
    let isDiscard = false;
    if (taskStore.modelStore.isFinishTask || taskStore.modelStore.isDiscard) {
      isFinishTask = taskStore.modelStore.isFinishTask;
      isDiscard = taskStore.modelStore.isDiscard;
    }
    return <div><GovernTag ecId={`${this && this.props && this.props.ecId || ''}_GovernTag@opgfwc`} record={field} isFinishTask={isFinishTask} isDiscard={isDiscard} /></div>;
  }
  // 重定义进度dom
  progressItem(field) {
    const { taskStore } = this.props;
    let percent = 0;
    if (field.value != '') {
      percent = field.value.replace('%', '');
      if (taskStore.modelStore.percent == 0) {
        percent = percent;
      } else {
        percent = taskStore.modelStore.percent;
      }
    } else {
      percent = 0;
    }
    return <div><WeaProgress ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@9to6lf`} percent={percent} strokeColor="#28ce87" /></div>;
  }

  // 获取上传组件
  getUploadItem(field, form) {
    const { listStore2 } = this.props;
    let { uploadSize, updateForm } = listStore2;
    let submitFlag = listStore2.submitFlag;
    let upload = {};
    return (<WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@ufqp4u`}
      ref={field.domkey[0]}
      viewAttr={field.viewAttr}
      uploadUrl={field.uploadUrl}
      category={field.category}
      autoUpload={field.otherParams.autoUpload}
      datas={field.datas}
      multiSelection={field.multiSelection}
      maxUploadSize={field.otherParams.maxUploadSize}
      getShowListDatas={(listT, listB) => {
        if (listB.length > 0 && !submitFlag) {
          upload[field.domkey] = 'xk';
          form.updateFields(upload);// 赋值绕过检验规则
        }
        updateForm(listT, listB, upload, form, field, uploadSize);
      }}
    />);
  }
}
@observer
class GetAdButtons extends React.Component {
  render() {
    const { listStore } = this.props;
    const { doSearch, clearFormFields, setShowSearchAd } = listStore;
    return [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@hmjfqr@search`} type="primary" onClick={() => { doSearch(); }}>{getLabel(197, '搜索')}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@2jetbs@reset`} type="ghost" onClick={() => { clearFormFields(); }}>{getLabel(2022, '重置')}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@o85q7g@cancel`} type="ghost" onClick={() => { setShowSearchAd(false); }}>{getLabel(201, '取消')}</Button>),
    ];
  }
}
const getAdButtons = (listStore) => {
  const { doSearch, setShowSearchAd, clearFormFields } = listStore;
  return [
    (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@infrsh@search`} type="primary" onClick={() => { doSearch(); setShowSearchAd(false); clearFormFields(); }}>{getLabel(197, '搜索')}</Button>),
    (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8xkqry@reset`} type="ghost" onClick={() => { clearFormFields(); }}>{getLabel(2022, '重置')}</Button>),
    (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@tlxm6p@cancel`} type="ghost" onClick={() => { setShowSearchAd(false); }}>{getLabel(31129, '取消')}</Button>),
  ];
};

export { Condition, GetAdButtons, ConditionNum, getAdButtons };
